"""
User-related resources for FastMCP
"""

from fastmcp import FastMCP, Context
from typing import Optional


class UserResources:
    """User-related resources for FastMCP."""

    def __init__(self, mcp: FastMCP):
        self.mcp = mcp
        # Sample user data
        self.USERS_DB = {
            1: {
                "id": 1,
                "name": "Alice Johnson",
                "email": "alice@example.com",
                "role": "admin",
                "active": True,
            },
            2: {
                "id": 2,
                "name": "Bob Smith",
                "email": "bob@example.com",
                "role": "user",
                "active": True,
            },
            3: {
                "id": 3,
                "name": "Charlie Brown",
                "email": "charlie@example.com",
                "role": "user",
                "active": False,
            },
            4: {
                "id": 4,
                "name": "Diana Prince",
                "email": "diana@example.com",
                "role": "moderator",
                "active": True,
            },
            5: {
                "id": 5,
                "name": "Eve Adams",
                "email": "eve@example.com",
                "role": "user",
                "active": True,
            },
        }

    def get_all_users(self) -> dict:
        """Get a list of all users."""
        return {
            "total_users": len(self.USERS_DB),
            "users": list(self.USERS_DB.values()),
        }

    async def get_user_profile(self, user_id: int, ctx: Context) -> dict:
        """Get detailed profile information for a specific user."""
        await ctx.info(f"Looking up user profile for ID: {user_id}")

        if user_id not in self.USERS_DB:
            return {
                "error": f"User with ID {user_id} not found",
                "available_users": list(self.USERS_DB.keys()),
            }

        user = self.USERS_DB[user_id]

        # Add some additional profile information
        profile = user.copy()
        profile.update(
            {
                "created_date": "2024-01-01",
                "last_login": "2024-07-29",
                "preferences": {
                    "theme": "dark",
                    "notifications": True,
                    "language": "en",
                },
                "statistics": {
                    "login_count": 42,
                    "projects_created": 5,
                    "files_uploaded": 23,
                },
            }
        )

        return profile

    def get_active_users(self) -> dict:
        """Get a list of active users only."""
        active_users = [user for user in self.USERS_DB.values() if user["active"]]

        return {
            "total_active": len(active_users),
            "total_inactive": len(self.USERS_DB) - len(active_users),
            "active_users": active_users,
        }

    def get_users_by_role(self, role: str) -> dict:
        """Get users filtered by their role."""
        filtered_users = [
            user
            for user in self.USERS_DB.values()
            if user["role"].lower() == role.lower()
        ]
        available_roles = list(set(user["role"] for user in self.USERS_DB.values()))

        return {
            "role": role,
            "available_roles": available_roles,
            "matching_users": len(filtered_users),
            "users": filtered_users,
        }

    def get_user_statistics(self) -> dict:
        """Get overall user statistics."""
        total_users = len(self.USERS_DB)
        active_users = len([u for u in self.USERS_DB.values() if u["active"]])
        inactive_users = total_users - active_users

        # Count by role
        role_counts = {}
        for user in self.USERS_DB.values():
            role = user["role"]
            role_counts[role] = role_counts.get(role, 0) + 1

        return {
            "total_users": total_users,
            "active_users": active_users,
            "inactive_users": inactive_users,
            "activity_rate": (
                round((active_users / total_users) * 100, 2) if total_users > 0 else 0
            ),
            "role_distribution": role_counts,
            "latest_user_id": max(self.USERS_DB.keys()) if self.USERS_DB else 0,
        }

    def register(self):
        """Register all user resources with FastMCP."""
        self.mcp.resource(
            uri="users://list",
            name="All Users",
            description="List of all users in the system",
            mime_type="application/json",
            tags={"users", "data"},
        )(self.get_all_users)

        self.mcp.resource(
            uri="users://{user_id}",
            name="User Profile",
            description="Get detailed information about a specific user",
            mime_type="application/json",
            tags={"users", "profile"},
        )(self.get_user_profile)

        self.mcp.resource(
            uri="users://active",
            name="Active Users",
            description="List of currently active users",
            mime_type="application/json",
            tags={"users", "active", "status"},
        )(self.get_active_users)

        self.mcp.resource(
            uri="users://roles/{role}",
            name="Users by Role",
            description="Get users filtered by their role",
            mime_type="application/json",
            tags={"users", "roles", "filter"},
        )(self.get_users_by_role)

        self.mcp.resource(
            uri="users://stats",
            name="User Statistics",
            description="Overall user statistics and metrics",
            mime_type="application/json",
            tags={"users", "statistics", "analytics"},
        )(self.get_user_statistics)
